import numpy as np
import cv2

src = cv2.imread('lawn.png')
src = cv2.cvtColor(src,cv2.COLOR_RGB2GRAY)

class Rect:
    def __init__(self,x,y,width,height):
        self.x=x
        self.y=y
        self.width=width
        self.height=height

def sum(img):
    total = 0
    h, w = img.shape[:2]
    for y in range(h):
        for x in range(w):
            val = img[y, x]
            total = total + val
    return total

def print_pixel(hint, img):
    h, w = img.shape[:2]
    print(hint)
    for y in range(h):
        for x in range(w):
            val = img[y, x]
            print(f'{x},{y}={val}')

def gradient(img):
    # 使用Scharr滤波器计算x和y方向的梯度
    sobelx = cv2.Sobel(img, cv2.CV_16SC1, 1, 0)
    sobely = cv2.Sobel(img, cv2.CV_16SC1, 0, 1)
    #sobelx = cv2.Scharr(img, cv2.CV_64F, 1, 0)
    #sobely = cv2.Scharr(img, cv2.CV_64F, 0, 1)
    print_pixel("======================================",sobelx)
    print_pixel("++++++++++++++++++++++++++++++++++++++",sobely)
    #sobelx = sobelx / 255.0
    #sobely = sobely / 255.0
    # 梯度平方
    sqr_grad_x = sobelx ** 2
    sqr_grad_y = sobely ** 2
    # 梯度方差
    var_grad = (sqr_grad_x + sqr_grad_y) / 2.0
    # 将方差转换到合理的显示范围
    var_grad_norm = cv2.normalize(var_grad, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
    return var_grad, var_grad_norm
    # 显示梯度方差图
    # cv2.imshow('Gradient Variance', var_grad_norm)

def canny(img):
    # 高斯模糊降低噪声
    gray = cv2.GaussianBlur(img,(3,3),0)
    #图像梯度
    xgrad=cv2.Sobel(gray, cv2.CV_16SC1, 1, 0)
    ygrad=cv2.Sobel(gray, cv2.CV_16SC1, 0, 1)
    #计算边缘
    # 参数必须符合1:3或1:2
    imCan=cv2.Canny(xgrad, ygrad, 60, 120)
    return imCan
    #cv2.imshow("edge",imCan)
    #cv2.imwrite("canny.png",imCan)
    # 彩色图
    #dst=cv2.bitwise_and(img,img,mask=edge_output)
    #cv2.imshow('cedge',dst)
    #cv2.imwrite("bitwise.png",dst)

def crop(img, rect):
    return img[rect.y:rect.y+rect.height, rect.x:rect.x+rect.width]

def demo():
    img_can = canny(src)

    boxes = []
    boxes.append(Rect(238, 172, 30, 30))
    boxes.append(Rect(187, 105, 30, 30))
    boxes.append(Rect(367, 172, 30, 30))

    for i in range(len(boxes)):
        img = crop(img_can, boxes[i])
        grad_var, grad_var_norm = gradient(img)
        cv2.imwrite("crop%d.png"%(i),img)
        gvs = sum(grad_var)
        print(f'id {i} sum {gvs}')
        #gvns = sum(grad_var_norm)
        #print(f'id {i} sum {gvs} norm {gvns}')
        cv2.imwrite("grad_var%d.png"%(i),grad_var_norm)

    #edge(src)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()

    # rows, cols = img_crop1.shape[:2]
    # print(f'type{type(img_crop1.shape)}')
    # print(f'h{rows} w{cols}')


if __name__ == "__main__":
    demo()